package controller;

import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.StringTokenizer;

import entity.Movie;

public class MovieDB {
	
	public static final String SEPARATOR = "|";
	public static final String filename = "movie.txt";

    // an example of reading
	public static ArrayList readMovies(String filename) throws IOException {
		
		// read String from text file
		ArrayList stringArray = (ArrayList)read(filename);
		ArrayList alr = new ArrayList() ;// to store Movies data
		
	     for (int i = 0 ; i < stringArray.size() ; i++) {
					String st = (String)stringArray.get(i);
					
					// get individual 'fields' of the string separated by SEPARATOR
					StringTokenizer star = new StringTokenizer(st , SEPARATOR);	// pass in the string to the string tokenizer using delimiter ","
					
					//Pass in token
					int MovieID = Integer.parseInt(star.nextToken().trim());
					String MovieName = star.nextToken().trim();
					String MovieReleaseDate = star.nextToken().trim();
					String MovieType = star.nextToken().trim();
					String MovieRating = star.nextToken().trim();
					String MovieStatus = star.nextToken().trim();
					String MovieDuration  = star.nextToken().trim();
					
					// create Movie object from file data
					Movie m1 = new Movie(MovieID, MovieName, MovieReleaseDate, MovieType, MovieRating,
							MovieStatus, MovieDuration);

					// add to Movies list
					alr.add(m1) ;
				}
				return alr ;
		
	}
	
	  // an example of saving
	public static void saveMovies(String filename, List al) throws IOException {
			List alw = new ArrayList() ;// to store Movies data
	
	        for (int i = 0 ; i < al.size() ; i++) {
					Movie m1 = (Movie)al.get(i);
					StringBuilder st =  new StringBuilder() ;
					st.append(m1.getMovieID());
					st.append(SEPARATOR);
					st.append(m1.getMovieName().trim());
					st.append(SEPARATOR);
					st.append(m1.getMovieReleaseDate().trim());
					st.append(SEPARATOR);
					st.append(m1.getMovieType().trim());
					st.append(SEPARATOR);
					st.append(m1.getMovieRating().trim());
					st.append(SEPARATOR);
					st.append(m1.getMovieStatus().trim());
					st.append(SEPARATOR);
					st.append(m1.getMovieDuration().trim());
					st.append(SEPARATOR);
					alw.add(st.toString()) ;
				}
				write(filename,alw);
		}

	public static List read(String fileName) throws IOException {
			List data = new ArrayList() ;
		    Scanner scanner = new Scanner(new FileInputStream(fileName));
		    try {
		      while (scanner.hasNextLine()){
		        data.add(scanner.nextLine());
		      }
		    }
		    finally{
		      scanner.close();
		    }
		    return data;
		  }

	/** Write fixed content to the given file. */
	public static void write(String fileName, List data) throws IOException  {
	    PrintWriter out = new PrintWriter(new FileWriter(fileName));
	
	    try {
			for (int i =0; i < data.size() ; i++) {
	      		out.println((String)data.get(i));
			}
	    }
	    finally {
	      out.close();
	    }
	  }

	public static void createMovie() throws IOException
	{
		Scanner sc = new Scanner(System.in);
		String filename = "movie.txt" ;
		ArrayList al = MovieDB.readMovies(filename) ;
		//String st = (String)stringArray;
		
		try{
			// get individual 'fields' of the string separated by SEPARATOR
			StringTokenizer star = new StringTokenizer(SEPARATOR);	// pass in the string to the string tokenizer using delimiter ","
			
			//Pass in token
			int movieID; 
			String movieName; 
			String movieReleaseDate;
			String movieType;
			String movieRating;
			String movieStatus;;
			String movieDuration;
			
			 System.out.println("Enter MovieID: ");
             movieID = sc.nextInt();
             System.out.println("Enter MovieName: ");
             movieName = sc.next();
             System.out.println("Enter MovieReleaseDate: ");
             movieReleaseDate = sc.next();
             System.out.println("Enter MovieType: ");
             movieType = sc.next();
             System.out.println("Enter MovieRating: ");
             movieRating = sc.next();
             System.out.println("Enter MovieStatus: ");
             movieStatus = sc.next();
             System.out.println("Enter MovieDuration: ");
             movieDuration = sc.next();
			
			// create Movie object from file data
			Movie m1 = new Movie(movieID, movieName, movieReleaseDate, movieType, movieRating,
					movieStatus, movieDuration);
			
			al.add(m1);
		
			// write Movie record/s to file.
			MovieDB.saveMovies(filename, al);
		
		}catch (IOException e) {
			System.out.println("IOException > " + e.getMessage());}
	}
	
	public static void deleteMovie() throws IOException {
		Scanner sc = new Scanner(System.in);
		ArrayList al = MovieDB.readMovies(filename) ;
		int elementMovieID;
		int confirmDelete=0;
		
		try{
			System.out.println("Enter MovieID to Delete: ");
			elementMovieID = sc.nextInt();
         
			for (int i = 0 ; i < al.size() ; i++) {
				 Movie m1 = (Movie)al.get(i);
				System.out.println("Movie ID: "+m1.getMovieID());
				System.out.println("Movie Name: " + m1.getMovieName() );
				System.out.println("Movie Duration: " + m1.getMovieType() );
         
        	 if(elementMovieID==m1.getMovieID()){
        		 System.out.println("Are you sure you want to delete this entry? (1 = yes, 0 = no)");
        		 System.out.println("Movie ID: "+m1.getMovieID());
    			 System.out.println("Movie Name: " + m1.getMovieName() );
    			 System.out.println("Movie Duration: " + m1.getMovieType());
    			 confirmDelete = sc.nextInt();
    			
    			if(confirmDelete==1){
    				System.out.println("Found and Removed");
    				al.remove(m1);
    				break;
    			}
    			
    			if(confirmDelete==0){
    				System.exit(0);
    			}
    			
    			else{
    				System.out.println("Error. System will exit.");
    				System.exit(0);
    			}

        	 }
        	 
			}

		 MovieDB.saveMovies(filename, al);
		}catch (IOException e) {
			System.out.println("IOException > " + e.getMessage());}
		
	}

	public static void updateMovie() throws IOException
	{
	    Scanner sc = new Scanner(System.in);
	    ArrayList al = MovieDB.readMovies(filename) ;
	    List <Movie> movie = new <Movie> ArrayList();
	    int elementMovieID;
	    int confirmUpdate=0;
	    int index = 0;
	    boolean end = false;
	    String value = "";

	    try{
	        System.out.println("Enter MovieID to Update: ");
	        elementMovieID = sc.nextInt();

	        for (int i = 0 ; i < al.size() ; i++) {
	            Movie m1 = (Movie)al.get(i);
	            System.out.println("Movie ID: "+m1.getMovieID());
	            System.out.println("Movie Name: " + m1.getMovieName() );
	            System.out.println("Movie Duration: " + m1.getMovieType() );
	            movie.add(m1);

	            if(elementMovieID==movie.get(i).getMovieID()){	
	                System.out.println("Enter the index to edit (1: Movie Name): ");
	                System.out.println("1: Movie Name: " + movie.get(i).getMovieName());
	                System.out.println("2: Movie Release Date: " + movie.get(i).getMovieReleaseDate() );
	                System.out.println("3: Movie Type: " + movie.get(i).getMovieType() );
	                System.out.println("4: Movie Rating: " + movie.get(i).getMovieRating() );
	                System.out.println("5: Movie Status: " + movie.get(i).getMovieStatus() );
	                System.out.println("6: Movie Duration: " + movie.get(i).getMovieDuration() );
	                index = sc.nextInt();
	                System.out.println("Please Update: ");
                    value = sc.next();
	                
	                switch(index){
	
	                case 1: 
	                	movie.get(i).setMovieName(value);
	                	end =true;
	                	break;	                		
	                case 2: 
	                	movie.get(i).setMovieReleaseDate(value);
	                	end =true;
	                	break;  		
	                case 3: 
	                	movie.get(i).setMovieType(value);
	                	end =true;;
	                	break;
	                case 4: 
	                	movie.get(i).setMovieRating(value);
	                	end =true;
	                	break;
	                case 5: 
	                	movie.get(i).setMovieStatus(value);
	                	end =true;
	                	break;
	                case 6: 
	                	movie.get(i).setMovieDuration(value);
	                	end =true;
	                	break;
	                }
	                if(end)break;
	                
	                al.remove(m1);
	                al.addAll(movie);
	               // al.add(movie);
	                
	            }
	        }
	        MovieDB.saveMovies(filename, al);
	    }catch (IOException e) {
	        System.out.println("IOException > " + e.getMessage());
	    }
	}
	
	public static void main(String[] aArgs) {
	    	int choice = 0;
	    	Scanner sc = new Scanner(System.in);

			do{
			    System.out.println("(1) Create Movie");
			    System.out.println("(2) Update Movie");
			    System.out.println("(3) Delete Movie");
			    System.out.println("(4) Show Movie");
			    System.out.println("(5) Exit");
			    
			    choice = sc.nextInt();
			    
			    switch(choice)
			    {
			    	case 1:
						try {
							createMovie();
						} catch (IOException e) {
							e.printStackTrace();
						}
						break;
			    	
			    	case 2:
			    		try {
							updateMovie();
						} catch (IOException e) {
							e.printStackTrace();
						}
						break;
			    	
			    	case 3:
			    		try {
							deleteMovie();
						} catch (IOException e) {
							e.printStackTrace();
						}
			    		break;
			    		
			    	case 4:
						try {
							// read file containing Movie records.
							ArrayList al = MovieDB.readMovies(filename) ;
							for (int i = 0 ; i < al.size() ; i++) {
									Movie m1 = (Movie)al.get(i);
									System.out.println("Movie Name: " + m1.getMovieName() );
									System.out.println("Movie Duration: " + m1.getMovieDuration() );
							}

						}catch (IOException e) {
							System.out.println("IOException > " + e.getMessage());}
			    		break;
			    		
			    	case 5:
			    		break;
			    }
			}while(choice!=5);
	  }

}
